﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Mongaba.Core;

namespace Mongaba
{
    static class MongabaProgram
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            foreach (Process process in Process.GetProcesses().Where(x => x.ProcessName == "Mongaba"))
            {
                if (Process.GetCurrentProcess().Id != process.Id)
                {
                    SetFocus(process.MainWindowHandle);
                    Application.Exit();
                    return;
                }
            }
            
            

            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
     
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            frmMainWindow.CheckForIllegalCrossThreadCalls = false;
            Console.SetOut(Debug.OutputWriter);
            Application.Run(new frmMainWindow());
            
            
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = (Exception)e.ExceptionObject;
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            catch
            {
                Application.Exit();
            }
        }
        private static DialogResult ShowThreadExceptionDialog(string title, Exception e)
        {
            //Console.WriteLine(e.Message);
            //Console.WriteLine(e.StackTrace);
            return DialogResult.Ignore;

        }


        static void Application_ThreadException(object sender, ThreadExceptionEventArgs t)
        {
            Console.WriteLine(t.Exception);
            Console.WriteLine(t.Exception);
            
        }

        static frmDebug frmDebug = null;
        public static frmDebug Debug
        {
            get {
                if (frmDebug == null)
                {
                    frmDebug = new frmDebug();
                }

                return frmDebug;
            }
        }

        [DllImport("user32.dll")]
        public static extern IntPtr SetFocus(IntPtr hWnd);
    }
}
